﻿//DANGTH CREATED

var ctrl,
    btn,
    activateACloneSaveWP,
    addNewWorkspace,
    editWorkspace,
    fillWorkspaceForm,
    submitWorkspace,
    resetForm,
    validate,
    selectionPreviewImage,
    activeWorkspace,
    postSave,
    preSave,
    promptSave,
    validateClientEmail,
    checkpaymentbyCard,
    adminJsonData,
    isChange,
    validateUpdating,
    validateFormActive,
    validateTargetEnvActive,
    sendAdminDefaultUserName,
    fillReadOnlyForm,
    fillEditForm,
    createCloneSave,
    validateCreating,
    getEnvironment;

//submit type enum
var submitType = {
    save : 'save',
    active : 'active',
    addNew : 'addNew',
    activateCloneSave : 'activeCloneSave',
};

//workspace status enum
var workspaceStatus = {
    saved : 'Saved',
    active : 'Activated',
    addNew : 'Deactivated',
    cloneSaved : 'Clone Saved',
    cloneCompleted : 'Clone Completed',
    completed : "Completed",
    activeWithoutStriata : 'Activated without Striata'
};

//Ajax URL to get the data
var ajaxUrl = {
    getWorkspace: "/Service/Services.aspx/GetWorkspace",
    getWorkspaces: "/Service/Services.aspx/GetWorkspaces",
    sendDefaultEmailInfo: '/Service/Services.aspx/SendAdminInfo',
    validateActiveClientId: '/Service/Services.aspx/ValidateActiveClientId',
    validateActiveClientShortName: '/Service/Services.aspx/ValidateActivateClientShortName',
    validateCreateWorkspaceName: '/Service/Services.aspx/ValidateCreateWorkspaceName',
    validateCreateClientID: '/Service/Services.aspx/ValidateCreateClientId',
    validateUpdateClientShortName: '/Service/Services.aspx/ValidateUpdateClientShortName',
    validateUpdateWorkspaceName: '/Service/Services.aspx/ValidateUpdateWorkspaceName',
    createCloneSavedWorkspace: '/Service/Services.aspx/CreateCloneSavedWorkspace',
    activateCloneSavedWorkspace: '/Service/Services.aspx/ActivateCloneSavedWorkspace'
    
};

columnNames = ["", "", "ID", "Source Env", "Target Env", "Workspace Name", "Client", "Status", "Created On", "Created By", "Last Modified", "Last Modify by", "Note"];

columnModel = [
    { "name": "Edit", "index": "Edit", "width": 20, "height": 20, "align": "left", "hidedlg": true, "fixed": true, "search": false, "classes": "editrow", "title": true, "hidden": false, "widthOrg": 20, "resizable": true, "sortable": true, "stype": "text" },
    { "name": "Clone", "index": "Edit", "width": 20, "height": 20, "align": "left", "hidedlg": true, "fixed": true, "search": false, "classes": "editrow", "title": true, "hidden": false, "widthOrg": 20, "resizable": true, "sortable": true, "stype": "text" },
    { "name": "WorkspaceId", "index": "pkWorkSpace_ID", "width": 100, "editable": false, "hidedlg": true, "hidden": true, "title": true, "widthOrg": 1, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "HostingEnvironmentName", "index": "HostingEnvName", "width": 60, "align": "center", "editable": false, "hidedlg": true, "hidden": false, "title": true, "widthOrg": 1, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "TargetEnvironmentName", "index": "TargetEnvName", "width": 60, "align": "center" , "editable": false, "hidden": false, "title": true, "widthOrg": 80, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "WorkspaceName", "index": "WorkSpaceName", "width": 100, "editable": false, "hidden": false, "title": true, "widthOrg": 80, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "ClientName", "index": "ClientName", "width": 80, "editable": false, "hidden": false, "title": true, "widthOrg": 80, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "WorkSpaceStatusName", "index": "WorkSpaceStatusName", "width": 30, "align": "center", "editable": false, "hidden": false, "title": true, "widthOrg": 100, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "CreatedOn", "index": "CreatedDate", "width": 60, "align": "center", "editable": false, "hidden": false, "title": true, "widthOrg": 60, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "CreatedBy", "index": "CreatedBy", "width": 50, "align": "center", "editable": false, "title": true, "hidden": false, "widthOrg": 80, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "LastModifiedOn", "index": "WSModifiedDate", "width": 40, "align": "center", "editable": false, "hidden": false, "searchoptions": { }, "title": true, "widthOrg": 40, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "LastModifiedBy", "index": "WSModifiedBy", "width": 60, "align": "center", "editable": false, "hidden": false, "searchoptions": { }, "title": true, "widthOrg": 60, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "WorkSpaceNote", "index": "WorkSpaceNote", "width": 80, "align": "left", "editable": false, "hidden": false, "searchoptions": { }, "title": true, "widthOrg": 80, "resizable": true, "sortable": true, "search": true, "stype": "text" }
];

    $(document).ready(function () {
        

        //$('#loaderwrapper').css('position', '1000');

        var showDetailNoNav;
        //PRIVATE VARIABLES    
        var intrnl = false;
        var sel_row;
        var gridRow;
        var grid = jQuery("#list");
        var overridepage = 0; //i need this for the resize column functionality.
        
        var nparams = { andor: '&&', items: [] };

        var advser = $("#advancedsearch").advSearch({
            colNames: [
                { disp: "Source Environment", valu: "HostingEnvName", typ: "str", srchop: [] },
                { disp: "Target Environment", valu: "TargetEnvName", typ: "str", srchop: [] },
                { disp: "Workspace Name", valu: "WorkSpaceName", typ: "str", srchop: [] },
                { disp: "Client", valu: "ClientName", typ: "str", srchop: [] },
                { disp: "Status", valu: "WorkSpaceStatusName", typ: "str", srchop: [] },
                { disp: "Created Date", valu: "CreatedDate", typ: "date", srchop: [] },
                { disp: "Created By", valu: "CreatedBy", typ: "str", srchop: [] },
                { disp: "Last Modify Date", valu: "WSModifiedDate", typ: "str", srchop: [] },
                { disp: "Last Modify By", valu: "WSModifiedBy", typ: "str", srchop: [] },
                { disp: "Note", valu: "WorkSpaceNote", typ: "str", srchop: [] }
            ],
            params: nparams
        });

//INITIALIZE CONTROLS AND IT'S OWN EVENTS
        ctrl = {
            //e --> edit control, r --> read only label
            wpname: { e: $('#txtWorkSpaceName'), r: null },
            wpnote: { e: $('#txtWorkSpaceNote'), r: null },
            wpstatus: { e: $('#lblStatus'), r: null },
            wpcreateDate: { e: $('#lbCreateDate'), r: null },
            wpcreateBy: { e: $('#lbCreateBy'), r: null },
            wplastModifyDate: { e: $('#lbLastModified'), r: null },
            wplastModifyBy: { e: $('#lbLastModifiedBy'), r: null },

            clAdminId: { e: $('#lblDPMAdminId'), r: null },
            clAdminPassword: { e: $('#lblDPMAdminPassword'), r: null },

            clName: { e: $('#txtClientName'), r: null },
            clId: { e: $('#txtClientId'), r: null },
            clContact: { e: $('#txtClientContactName'), r: null },
            clEmail: { e: $('#txtClientEmail'), r: null },
            clWebsite: { e: $('#txtClientWebsite'), r: null },
            clAddress1: { e: $('#txtClientAddress1'), r: null },
            clAddress2: { e: $('#txtClientAddress2'), r: null },
            clPhone1: { e: $('#txtClientTelephone1'), r: null },
            clPhone2: { e: $('#txtClientTelephone2'), r: null },
            clFax: { e: $('#txtClientFax'), r: null },
            clCity: { e: $('#txtClientCity'), r: null },
            clState: { e: $('#txtClientStateProv'), r: null },
            clPostCode: { e: $('#txtClientPostalCode'), r: null },
            clCountry: { e: $('#txtClientCountry'), r: null },
            clpkClientID: { e: $('#pkClientId'), r: null },
            clWebPay: { e: $('#chkClientWebPayment'), r: null },
            clACH: { e: $('#chkClientACHPayment'), r: null },
            clDebit: { e: $('#chkClientDebitPayment'), r: null },
            clCredit: { e: $('#chkClientCreditCardPayment'), r: null },
            clVisa: { e: $('#chkClientVisaCardPayment'), r: null },
            clMaster: { e: $('#chkClientMasterCardPayment'), r: null },
            clAME: { e: $('#chkClientAmericanExpressCardPayment'), r: null },
            clDiscover: { e: $('#chkClientDiscoverNetworkCardPayment'), r: null },
            clShortName: { e: $('#txtClientShortName'), r: null },
            striaDesc: { e: $('#txtStriataDescription'), r: null },
            striaAddress: { e: $('#txtStriataAddress'), r: null },
            striaUser: { e: $('#txtStriataUsername'), r: null },
            striaPass: { e: $('#txtStriataPassword'), r: null },
            fedDesc: { e: $('#txtFedPayDescription'), r: null },
            fedAddress: { e: $('#txtFedPayAddress'), r: null },
            fedUser: { e: $('#txtFedPayUsername'), r: null },
            fedPass: { e: $('#txtFedPayPassword'), r: null },
            optinY: {
                e: $('#autooptin_Yes'),
                r: null,
                showe: function() {
                    ctrl.optinY.e.parent().show();
                },
                showr: function() {
                    ctrl.optinY.e.parent().hide();
                }
            },
            optinN: { e: $('#autooptin_No'), r: null },

            optoutY: {
                e: $('#autooptout_Yes'),
                r: null,
                showe: function() {
                    ctrl.optoutY.e.parent().show();
                },
                showr: function() {
                    ctrl.optoutY.e.parent().hide();
                }
            },
            optoutN: { e: $('#autooptout_No'), r: null },

            printmachaddY: {
                e: $('#printmachadd_Yes'),
                r: null,
                showe: function() {
                    ctrl.printmachaddY.e.parent().show();
                },
                showr: function() {
                    ctrl.printmachaddY.e.parent().hide();
                }
            },
            printmachaddN: { e: $('#printmachadd_No'), r: null },

            printachOptinY: {
                e: $('#radioPrintachOptin_Yes'),
                r: null,
                showe: function() {
                    ctrl.printachOptinY.e.parent().show();
                },
                showr: function() {
                    ctrl.printachOptinY.e.parent().hide();
                }
            },
            printachOptinN: { e: $('#radioPrintachOptin_No'), r: null },

            optindays: { e: $('#optindays'), r: null },

            defaultpmY: {
                e: $('#defaultpm_Yes'),
                r: null,
                showe: function() {
                    ctrl.defaultpmY.e.parent().show();
                },
                showr: function() {
                    ctrl.defaultpmY.e.parent().hide();
                }
            },
            defaultpmN: { e: $('#defaultpm_No'), r: null },

            accpaysetY: {
                e: $('#accpayset_Yes'),
                r: null,
                showe: function() {
                    ctrl.accpaysetY.e.parent().show();
                },
                showr: function() {
                    ctrl.accpaysetY.e.parent().hide();
                }
            },
            accpaysetN: { e: $('#accpayset_No'), r: null },

            initialize: function() {
                $.each(ctrl, function(index, value) {
                    if (value.e) {
                        value.e.attr('tabindex', index);
                        value.e.change(function() {
                            isChange = true;
                        });

                        //create readonly label.
                        value.r = $('<label/>').hide();
                        value.e.parent().append(value.r);
                    }
                });

                ctrl.optinY.e.parent().parent().append(ctrl.optinY.r);
                ctrl.optinY.r.css('margin-left', '45%');

                ctrl.optoutY.e.parent().parent().append(ctrl.optoutY.r);
                ctrl.optoutY.r.css('margin-left', '45%');

                ctrl.printmachaddY.e.parent().parent().append(ctrl.printmachaddY.r);
                ctrl.printmachaddY.r.css('margin-left', '45%');

                ctrl.printachOptinY.e.parent().parent().append(ctrl.printachOptinY.r);
                ctrl.printachOptinY.r.css('margin-left', '45%');

                ctrl.defaultpmY.e.parent().parent().append(ctrl.defaultpmY.r);
                ctrl.defaultpmY.r.css('margin-left', '45%');

                ctrl.accpaysetY.e.parent().parent().append(ctrl.accpaysetY.r);
                ctrl.accpaysetY.r.css('margin-left', '45%');

                ctrl.clShortName.e.keydown(function ()
                {
                    
                    if (event.keyCode == 32){  //space character is not allowed
                        event.returnValue = false;
                    }
                });
            },
        };

        btn = {
            dtCancel: $('.detailcancel'),
            dtSave : $('.detailsave'),
            dtAdd : $('.detailadd'),
            dtActive : $('.detailactivate'),
            activate : $('.btnActive'),
            activeCancel : $('.btnActiveCancel'),
            initialize : function () {
                
                btn.dtCancel.click(function() {
                    
                    if(isChange) {
                        var confirmResult = confirm("Are you sure you want to leave this page?");
                        if(!confirmResult) {
                            return false;
                        }
                    }

                    var frmUserdetails = $('#frmuserdetails');

                    frmUserdetails
                        .stop()
                        .find('.jfVal,.jValCover')
                        .stop()
                        .remove()
                        .end()
                        .find('.jVal,[jVal]')
                        .css({ position: '', borderColor: '', left: '0px', top: '0px' })
                        .parent()
                        .find('.jValRelWrap')
                        .remove();

                    frmUserdetails
                        .stop()
                        .find('.jValSpacer,.jValSpacercover')
                        .stop()
                        .remove()
                        .end();
                    
                    ShowGrid();
                    $("#list").trigger("reloadGrid");
                    $('#loaderwrapper').hide();
                    resetForm();
                    
                    return false;
                });

                btn.activeCancel.click(function() {
                    $('#activeWindowsModal').dialog("close");
                    return false;
                });

                btn.dtSave.click(function() {
                    var validateResult = validateUpdating();
                    if(validateResult) {
                        submitWorkspace(submitType.save);    
                    }
                    return false;
                });

                btn.dtAdd.click(function() {
                    var validateResult = validateCreating();
                    if (validateResult) {
                        submitWorkspace(submitType.addNew);
                    }
                    return false;
                });

                //show-up active dialog window.
                btn.dtActive.click(function() {
                    var validateActiveResult = validateFormActive();
                    if (validateActiveResult) {
                        //activate a clone save workspace
                        var modalformHeight;
                        var modalformWidth;
                        if (ctrl.wpstatus.e.text() == workspaceStatus.cloneSaved) {
                            $('#activeForm').hide();
                            $('#activateCloneSaveForm').show();
                            modalformHeight = 450;
                            modalformWidth = 500;
                        }
                        else {
                            $('#activeForm').show();
                            $('#activateCloneSaveForm').hide();
                            modalformHeight = 230;
                            modalformWidth = 404;
                        }
                        //Show up active dialog box.
                        $('#activeWindowsModal').dialog({
                            autoOpen: true,
                            resizable: false,
                            height: modalformHeight,
                            width: modalformWidth,
                            modal: true,
                            beforeClose: function(event, ui) {
                                
                            },
                        });
                        
                        $('.ui-dialog-titlebar-close').hide();
                    }
                    return false;
                });

                //call to server active function.
                btn.activate.click(function() {
                    $('#environment').val(ctrl.wpstatus.e.text() == workspaceStatus.cloneSaved ? $('#selectEnvironment2').val() : $('#selectEnvironment').val());
                    $('#wspId').val(gridRow.WorkspaceId); //Set workspace Id for posting to server.
                    activeWorkspace();
                    return false;
                });
            }
        };
     
//EVENTS
        $(".form_table input:checkbox").click(function() {
            promptSave();
        });
        
        $('.form_txt').keydown(function() {
            promptSave();
        });
        
        $('.form_txtarea').keydown(function() {
            promptSave();
        });
        
        //upload logo event
        $('.form_select').change(function() {
            promptSave();
        });
        
        $('#btn_upload').click(function() {
            $('#clientFileUpload').click();
        });
        
        $('#clientFileUpload').change(function() {
            selectionPreviewImage(this.files, this.value);
        });
        
        $('#chkClientCreditCardPayment').change(function() {
            checkpaymentbyCard();
        });

        $('#btnSendEmail').click(function () {
            //validate email format before send.
            var validateEmail = $('#sendEmailForm').jVal({ style: 'cover', padding: 3, border: 1, wrap: true });
            if (validateEmail) {
                adminJsonData.ToEmailAdress = $('#txtSendingEmailAddress').val();
                sendAdminDefaultUserName(adminJsonData);
                $('#activeWindowsModal').dialog("close");
                ShowGrid();
                reloadData('UserData');
                $('#loaderwrapper').hide();
                resetForm();
            }
        });

        $('#user').change(function () {
            if ($('#user').is(':checked')) {
                $('#userRoles')
                    .attr('checked', 'checked')
                    .attr("disabled","disabled");
            }
            else {
                $('#userRoles').removeAttr("disabled");
            }
        });
        
        addNewWorkspace = function() {
            intrnl = true;
            showDetailNoNav();
            btn.dtActive.hide();
            $('#btn_upload').show();
            btn.dtAdd.show();
            btn.dtSave.hide();
            ctrl.wpname.e.focus();
            $.each($('ul.value_1x4'), function(index, value) {
                $($(value).children()[0]).css('margin-right', '');
                $($(value).children()[1]).show();
            });

            //Show edit controls - Hide readOnly text
            $.each(ctrl, function(index, value) {
                if (value.e && value.r) {
                    value.e.show();
                    value.r.hide();
                    if(value.showe)
                        value.showe();
                }
            });
        };
        
        showDetailNoNav = function() {
            $('#panel_grid_main').hide();
            $('#panel_grid_sub').show();
            $('#panel_tabs').show();
            preSave(intrnl);
            try {
                var containerwidth = $('#second_grid_container').width();
                $('#second_list').jqGrid('setGridWidth', containerwidth - 2);
            } catch(err) {

            }
        };
        
//CREATE NEW WORKSPACE
        //validation
        validateCreating = function() {
            //validate form
            var frmvisualvalid = $('#workspaceDetail-1').jVal({ style: 'cover', padding: 3, border: 1, wrap: true });
            if (!frmvisualvalid) {
                alert("CHECK FIELDS HIGHLIGHTED IN RED:\n\nThere are missing or invalid values given.  please correct the identified fields, and re-submit.");
                return false;
            }
            
            var workspaceName = ctrl.wpname.e.val();
            var hidsearchid = $('#hidsearchid').val();
            var jsondata = '{seid:"' + hidsearchid + '", workspaceName:"' + workspaceName + '"}';
            
            //validate workspace name existed or not
            var validateWorkspaceNameResult = true;
            var validateClientIdResult = true;
            var validateClientIdjval, validateWorkspaceJval;
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: ajaxUrl.validateCreateWorkspaceName,
                async: false,
                data: jsondata,
                dataType: "json",
                success: function(data, textStatus) {
                    data = jQuery.parseJSON(data.d); 
                    if (!data.validateResult) {
                        validateWorkspaceJval = ctrl.wpname.e.attr('jVal');
                        var existed = "{valid:function (val) { return 'existed';}}";
                        ctrl.wpname.e.attr('jVal', existed);
                        //show-up existed workspace name
                        validateWorkspaceNameResult = false;
                    }
                    
                },
                error: function(data, textStatus) {
                    alert('An error has occured retrieving data!');
                    validateWorkspaceNameResult = false;
                }
            });
            
            //validate clientId existed or not
            jsondata = '{seid:"' + hidsearchid + '", clientId:"' + ctrl.clId.e.val() + '"}';
              $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: ajaxUrl.validateCreateClientID,
                async: false,
                data: jsondata,
                dataType: "json",
                success: function(data, textStatus) {
                    data = jQuery.parseJSON(data.d); 
                    if (!data.validateResult) {
                        validateClientIdjval = ctrl.clId.e.attr('jVal');
                        var existed = "{valid:function (val) { return 'existed';}}";
                        ctrl.clId.e.attr('jVal', existed);
                        //show-up existed workspace name
                        validateClientIdResult = false;
                    }
                    
                },
                error: function(data, textStatus) {
                    alert('An error has occured retrieving data!');
                    validateWorkspaceNameResult = false;
                }
            });
            
            $('#workspaceDetail-1').jVal({ style: 'cover', padding: 3, border: 1, wrap: true });
            if(validateWorkspaceJval) {
                ctrl.wpname.e.attr('jVal', validateWorkspaceJval);
            }
            if(validateClientIdjval) {
                ctrl.clId.e.attr('jVal', validateClientIdjval);
            }
            
            return validateWorkspaceNameResult && validateClientIdResult;
        };        

//SAVE
        validateUpdating = function() {

            //validate form
            var frmvisualvalid = $('#workspaceDetail-1').jVal({ style: 'cover', padding: 3, border: 1, wrap: true });
            if (!frmvisualvalid) {
                alert("CHECK FIELDS HIGHLIGHTED IN RED:\n\nThere are missing or invalid values given.  please correct the identified fields, and re-submit.");
                return false;
            }

            var hidsearchid = $('#hidsearchid').val();
            var targetEnvironment = gridRow.TargetEnvironmentName;
            var clientId = ctrl.clId.e.val() == '' ? ctrl.clId.r.text() : ctrl.clId.e.val();
            var workspaceValidateResult = false;
            var clientShortNameValidateResult = true;
            var workspaceChecknullJVal, clientShortNameChecknullJVal;
            
            //validate workspaceName
            var jsondata = '{seid:"' + hidsearchid + '", workspaceId:"' + gridRow.WorkspaceId + '", workSpaceName:"' + ctrl.wpname.e.val() + '"}';
              $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: ajaxUrl.validateUpdateWorkspaceName,
                    async: false,
                    data: jsondata,
                    dataType: "json",
                    success: function(data, textStatus) {
                        data = jQuery.parseJSON(data.d);
                        if (!data.validateResult) {
                            alert(data.errorMessage);
                            workspaceChecknullJVal = ctrl.wpname.e.attr('jVal');
                            var existed = "{valid:function (val) { return 'existed';}}";
                            ctrl.wpname.e.attr('jVal', existed);
                        }

                        workspaceValidateResult = data.validateResult;
                    },
                    error: function(data, textStatus) {
                        alert('An error has occured retrieving data!');
                        workspaceValidateResult = false;
                    }
                });

            //validate update clientShortName --> clientShortName must be unique
            if (targetEnvironment != "") {
                var clientShortName = ctrl.clShortName.e.val();
                jsondata = '{seid:"' + hidsearchid + '", clientId:"' + clientId + '", clientShortName:"' + clientShortName + '", targetEnvironment:"' + targetEnvironment + '"}';
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: ajaxUrl.validateUpdateClientShortName,
                    async: false,
                    data: jsondata,
                    dataType: "json",
                    success: function(data, textStatus) {
                        data = jQuery.parseJSON(data.d);
                        if (!data.validateResult) {
                            alert(data.errorMessage);
                            var existed = "{valid:function (val) { return 'existed';}}";
                            ctrl.clShortName.e.attr('jVal', existed);
                        }
                        clientShortNameValidateResult = data.validateResult;
                    },
                    error: function(data, textStatus) {
                        alert('An error has occured retrieving data!');
                        clientShortNameValidateResult = false;
                    }
                });
            }
            else {
                clientShortNameValidateResult = true;
            }
            
             $('#workspaceDetail-1').jVal({ style: 'cover', padding: 3, border: 1, wrap: true });

            if (workspaceChecknullJVal) ctrl.wpname.e.attr('jVal', workspaceChecknullJVal);
            ctrl.clShortName.e.removeAttr('jVal');

            return (workspaceValidateResult && clientShortNameValidateResult);
        };

//ACTIVE 
        //Event for active button
        activeWorkspace = function() {
            if(validateTargetEnvActive()) { //validate target environment before active
                if(ctrl.wpstatus.e.text() == workspaceStatus.cloneSaved) {
                    activateACloneSaveWP();
                }
                else {
                    submitWorkspace(submitType.active);        
                }
            }
        };


        activateACloneSaveWP = function() {
            var jsonObject = new Object();
            jsonObject.workspaceId = gridRow.WorkspaceId;
            jsonObject.targetEnvironment = $('#environment').val();
            jsonObject.userRoles = $('#userRoles').is(':checked') ? 1 : 0;
            jsonObject.user = $('#user').is(':checked') ? 1 : 0;
            jsonObject.systemPreferences = $('#systemPreferences').is(':checked') ? 1 : 0;
            jsonObject.templates = $('#templates').is(':checked') ? 1 : 0;
            jsonObject.logo = $('#logo').is(':checked') ? 1 : 0;
            jsonObject.templateRate = $('#templateRate').is(':checked') ? 1 : 0;
            $('#activateCloneSaveInfo').val(JSON.stringify(jsonObject));
            submitWorkspace(submitType.activateCloneSave);
           
        };

        //validate form active
        validateFormActive = function() {
            var classRequire = 'required';
            var jvalCheckNull = "{valid:function (val) { if (jQuery.trim(val).length < 1) return 'missing'; else return ''; }}";
            //Declare controls that must be validated for empty value.
            var notNullControls = [
                ctrl.clCity.e,
                ctrl.clState.e,
                ctrl.clPostCode.e,
                ctrl.clCountry.e,
                ctrl.clWebsite.e,
                ctrl.clShortName.e
            ];
            
            //Add active condition.
            $.each(notNullControls, function(index, control) {
                control.addClass(classRequire).attr('jVal', jvalCheckNull);
            });
            
            //Validate before active.
            var frmvisualvalid = $('#workspaceDetail-1').jVal({ style: 'cover', padding: 3, border: 1, wrap: true });
            
            //Remove active condition --> to remove conflict conditions between SAVE and ACTIVE action.
            $.each(notNullControls, function(index, control) {
                control.removeClass(classRequire).removeAttr('jVal');
            });

            //Return validation result if validate form is false.
            if(!frmvisualvalid) {
                
                //Show  alert message.
                alert("CHECK FIELDS HIGHLIGHTED IN RED:\n\nThere are missing or invalid values given.  please correct the identified fields, and re-active.");

                //Close Active dialog box for user to update value.
                $('#activeWindowsModal').dialog("close");
            } 
            
            return frmvisualvalid;  
        };
        
        //validate target environment.
        validateTargetEnvActive = function() {
           
           //Validate client Id on selected workspace
            var hidsearchid = $('#hidsearchid').val();
            var selectedEnvironment = $('#environment').val();
            var clientId = ctrl.clId.e.val() == '' ? ctrl.clId.r.text() : ctrl.clId.e.val();
            var validateResult = false;
             $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: ajaxUrl.validateActiveClientId,
                async: false,
                data: '{seid:"' + hidsearchid + '", clientId:"' + clientId + '", targetEnvironment:"' + selectedEnvironment + '"}',
                dataType: "json",
                success: function(data, textStatus)
                {
                    data = jQuery.parseJSON(data.d); 
                    if (!data.validateResult) {
                        //Close Active dialog box for user to update value.
                        $('#activeWindowsModal').dialog("close");
                        
                        alert(data.errorMessage);
                    }

                    validateResult =  data.validateResult;
                },
                error: function(data, textStatus)
                {
                    alert('An error has occured retrieving data!');
                    validateResult = false;
                }
            });

            if(!validateResult) return validateResult;
            
            //Validate client short name
            var clientShortName = ctrl.clShortName.e.val() == '' ? ctrl.clShortName.r.text() : ctrl.clShortName.e.val();
              $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: ajaxUrl.validateActiveClientShortName,
                async: false,
                data: '{seid:"' + hidsearchid + '", clientShortName:"' + clientShortName + '", targetEnvironment:"' + selectedEnvironment + '"}',
                dataType: "json",
                success: function(data, textStatus)
                {
                    data = jQuery.parseJSON(data.d); 
                    if (!data.validateResult) {
                        alert(data.errorMessage);
                        var checknullJVal = ctrl.clShortName.e.attr('jVal');
                        var existed = "{valid:function (val) { return 'existed';}}";
                        ctrl.clShortName.e.attr('jVal', existed);
                        //show-up existed workspace name
                        $('#workspaceDetail-1').jVal({ style: 'cover', padding: 3, border: 1, wrap: true });
                        ctrl.clShortName.e.attr('jVal', checknullJVal);
                        //Close Active dialog box for user to update value.
                        $('#activeWindowsModal').dialog("close");
                        
                    }

                    validateResult =  data.validateResult;
                },
                error: function(data, textStatus)
                {
                    alert('An error has occured retrieving data!');
                    validateResult = false;
                }
            });
            return validateResult;
        };

        //send default admin username and password for action function
        sendAdminDefaultUserName = function(emailData) {
            var hidsearchid = $('#hidsearchid').val();
            var params = '{seid:"' + hidsearchid + '", json:' + JSON.stringify(emailData) + '}';
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: ajaxUrl.sendDefaultEmailInfo,
                async: false,
                data: params,
                dataType: "json",
                success: function(data, textStatus) {
                    var sendResult = jQuery.parseJSON(data.d);
                    if (sendResult.sendResult) {
                        alert('Activate workspace successfully');
                        ShowGrid();
                        $('#activeWindowsModal').dialog("close");
                        reloadData('UserData');
                        $('#loaderwrapper').hide();
                        resetForm();
                        return;
                    }
                    else {
                        alert(sendResult.errorMessage);
                    }
                },
                error: function(data, textStatus) {
                    alert('An error has occured retrieving data!');
                }
            });
        };

//CLONING

        createCloneSave = function(rowId) {
            var confirmResult = confirm("This function will clone the selected client workspace");
            if (!confirmResult) return false;
            
            $('#loaderwrapper').show();
            gridRow = jQuery("#list").getRowData(rowId);
            var workspaceId = gridRow.WorkspaceId;
            var hidsearchid = $('#hidsearchid').val();
              $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: ajaxUrl.createCloneSavedWorkspace,
                async: true,
                data: '{seid:"' + hidsearchid + '", workspaceId:"' + workspaceId + '"}',
                dataType: "json",
                success: function(data, textStatus)
                {
                    data = jQuery.parseJSON(data.d); 
                    if (data.errorMessage != "") {
                        alert(data.errorMessage);
                    }
                    else {
                        alert('Clone successfully');
                        ShowGrid();
                        reloadData('UserData');
                    }
                    $('#loaderwrapper').hide();
                    
                },
                error: function(data, textStatus)
                {
                    alert('An error has occured retrieving data!');
                    $('#loaderwrapper').hide();
                }
            });
        };
        
//FORM
        FillUserForm = function(rowdata) {
            ShowDetailNoNav();
            btn.dtAdd.hide();
            btn.dtSave.show();
            $('.detaildelete').show();
            $('.notnew').show();
            $('.isnew').hide();
        };
        
//LOAD ENVIRONMENT LIST
        getEnvironment = function() {
            //Ajax call to service to get environment data.
            var dropdownResponse = FillDropdown("GetEnvironment");
            //bind to dropdown list
            $.each(dropdownResponse, function(index, value) {
                var optionItem = $('<option></option>').val(value).text(value);
                $('#selectEnvironment').append(optionItem);
                $('#selectEnvironment2').append(optionItem.clone());
            });
        };

//FILL FORM DATA
        fillReadOnlyForm = function(workspaceData) {
            var wp = workspaceData.wp;
            var cl = workspaceData.client;
            var clIO = workspaceData.clientIO;

            //Workspace 
            ctrl.wpname.r.text(wp.WorkSpaceName);
            ctrl.wpnote.r.text(wp.WorkSpaceNote);
            ctrl.wpstatus.r.text(wp.WorkSpaceStatusName);
            ctrl.wpcreateDate.r.text(workspaceData.workspaceCreateDate);
            ctrl.wpcreateBy.r.text(wp.CreatedBy);
            ctrl.wplastModifyDate.r.text(workspaceData.workspaceModifyDate);
            ctrl.wplastModifyBy.r.text(wp.WSModifiedBy);

            //Client Information
            ctrl.clName.r.text(cl.ClientName);
            ctrl.clId.r.text(cl.ClientID);
            ctrl.clId.e.val(cl.ClientID);

            ctrl.clAdminId.e.text(clIO.DPMAdminLogin);
            ctrl.clAdminId.r.text(clIO.DPMAdminLogin);

            ctrl.clAdminPassword.e.text(clIO.DPMAdminPassword);
            ctrl.clAdminPassword.r.text(clIO.DPMAdminPassword);

            ctrl.clContact.r.text(cl.ContactName);
            ctrl.clEmail.r.text(cl.Email);
            ctrl.clWebsite.r.text(cl.WebSite);
            ctrl.clAddress1.r.text(cl.Address1);
            ctrl.clAddress2.r.text(cl.Address2);
            ctrl.clPhone1.r.text(cl.Phone1);
            ctrl.clPhone2.r.text(cl.Phone2);
            ctrl.clFax.r.text(cl.Fax);
            ctrl.clCity.r.text(cl.City);
            ctrl.clState.r.text(cl.StateProv);
            ctrl.clPostCode.r.text(cl.PostalCode);
            ctrl.clCountry.r.text(cl.Country);
            ctrl.clpkClientID.r.text(cl.pkClient_ID);

            //Accepted Payments
            ctrl.clWebPay.r.text(cl.WebPayment == 'Y' ? 'Yes' : 'No');
            ctrl.clACH.r.text(cl.ACHPayment == 'Y' ? 'Yes' : 'No');
            ctrl.clDebit.r.text(cl.DebitPayment == 'Y' ? 'Yes' : 'No');
            ctrl.clCredit.r.text(cl.CreditPayment == 'Y' ? 'Yes' : 'No');
            ctrl.clVisa.r.text(cl.VISA == 'Y' ? 'Yes' : 'No');
            ctrl.clMaster.r.text(cl.Mastercard == 'Y' ? 'Yes' : 'No');
            ctrl.clAME.r.text(cl.AMEX == 'Y' ? 'Yes' : 'No');
            ctrl.clDiscover.r.text(cl.Discover == 'Y' ? 'Yes' : 'No');

            //Connection Information
            ctrl.clShortName.r.text(clIO.ClientShortName);
            ctrl.striaDesc.r.text(clIO.StriataServerDesc);
            ctrl.striaAddress.r.text(clIO.StriataServerNameOrIP);
            ctrl.striaUser.r.text(clIO.StriataUsername);
            ctrl.striaPass.r.text(clIO.StriataUserPW);
            ctrl.fedDesc.r.text(clIO.FedPayServerDesc);
            ctrl.fedAddress.r.text(clIO.FedPayServerNameOrIP);
            ctrl.fedUser.r.text(clIO.FedPayUsername);
            ctrl.fedPass.r.text(clIO.FedPayUserPW);


            //System Preferences
            ctrl.optindays.r.text(cl.CustomerStatusTimeOut);

            var subscribeRptUpdate = Boolean(cl.SubscribeRptUpdate);
            ctrl.optinY.r.text(subscribeRptUpdate ? 'Yes' : 'No');

            var unsubscribeRptUpdate = Boolean(cl.UnsubscribeRptUpdate);
            ctrl.optoutY.r.text(unsubscribeRptUpdate ? 'Yes' : 'No');

            var pMOverrideCustomer = Boolean(cl.PMOverrideCustomer);
            ctrl.printmachaddY.r.text(pMOverrideCustomer ? 'Yes' : 'No');

            var pMAllowIntro = Boolean(cl.PMAllowIntro);
            ctrl.printachOptinY.r.text(pMAllowIntro ? 'Yes' : 'No');

            var clientDefaultInfo = Boolean(cl.ClientDefaultInfo);
            ctrl.defaultpmY.r.text(clientDefaultInfo ? 'Yes' : 'No');

            var useClientPaymentMethod = Boolean(cl.UseClientPaymentMethod);
            ctrl.accpaysetY.r.text(useClientPaymentMethod ? 'Yes' : 'No');

            //Show readOnly text - Hide edit controls
            $.each(ctrl, function(index, value) {
                if (value.e && value.r) {
                    value.e.hide();
                    value.r.show();
                    if (value.showr)
                        value.showr();
                }
            });

            ctrl.clpkClientID.r.hide();

            //Set Image logo
            $('#btn_upload').show();
            if (workspaceData.logo != "") {
                $('#previewLogoImage')
                    .css('background-image', 'url(' + workspaceData.logo + ')')
                    .show();
            } else {
                $('#previewLogoImage').hide();
            }
            $('#clientFileUpload').hide();

            $.each($('ul.value_1x4'), function(index, value) {
                $($(value).children()[0]).css('margin-right', '200px');
                $($(value).children()[1]).hide();
            });

            //hide stars label after require field's label
            $('td.req > span').hide();

            $('#btn_upload').hide();
            btn.dtSave.hide();
            btn.dtActive.hide();
        },        
        fillCloneSave = function(workspaceData) {

        };

        fillWorkspaceForm = function(workspaceData) {
            if(workspaceData.wp.WorkSpaceStatusName == workspaceStatus.completed ||
               workspaceData.wp.WorkSpaceStatusName == workspaceStatus.cloneCompleted) { 
                fillReadOnlyForm(workspaceData);
                return;
            }

            //detect json data
            var wp = workspaceData.wp;
            var cl = workspaceData.client;
            var clIO = workspaceData.clientIO;

            //Workspace 
            ctrl.wpname.e.val(wp.WorkSpaceName).show();
            ctrl.wpnote.e.val(wp.WorkSpaceNote).show();
            ctrl.wpstatus.e.text(wp.WorkSpaceStatusName);
            ctrl.wpcreateDate.e.text(workspaceData.workspaceCreateDate);
            ctrl.wpcreateBy.e.text(wp.CreatedBy);
            ctrl.wplastModifyDate.e.text(workspaceData.workspaceModifyDate);
            ctrl.wplastModifyBy.e.text(wp.WSModifiedBy);
            
            //Client Information
            ctrl.clName.e.val(cl.ClientName);
            ctrl.clId.e.val(cl.ClientID);
            ctrl.clAdminId.e.text(clIO.DPMAdminLogin);
            ctrl.clAdminPassword.e.text(clIO.DPMAdminLogin);
            
            ctrl.clAdminPassword.e.text(clIO.DPMAdminPassword);
            ctrl.clAdminPassword.r.text(clIO.DPMAdminPassword);
            
            ctrl.clContact.e.val(cl.ContactName);
            ctrl.clEmail.e.val(cl.Email);
            ctrl.clWebsite.e.val(cl.WebSite);
            ctrl.clAddress1.e.val(cl.Address1);
            ctrl.clAddress2.e.val(cl.Address2);
            ctrl.clPhone1.e.val(cl.Phone1);
            ctrl.clPhone2.e.val(cl.Phone2);
            ctrl.clFax.e.val(cl.Fax);
            ctrl.clCity.e.val(cl.City);
            ctrl.clState.e.val(cl.StateProv);
            ctrl.clPostCode.e.val(cl.PostalCode);
            ctrl.clCountry.e.val(cl.Country); 
            ctrl.clpkClientID.e.val(cl.pkClient_ID);
            
            //Accepted Payments
            ctrl.clWebPay.e.attr('checked', cl.WebPayment == 'Y' ? true : false);
            ctrl.clACH.e.attr('checked', cl.ACHPayment == 'Y' ? true : false);
            ctrl.clDebit.e.attr('checked', cl.DebitPayment == 'Y' ? true : false);
            if (cl.CreditPayment == 'Y') {
                ctrl.clCredit.e.attr('checked', true);
                ctrl.clVisa.e.removeAttr('disabled');
                ctrl.clMaster.e.removeAttr('disabled');
                ctrl.clAME.e.removeAttr('disabled');
                ctrl.clDiscover.e.removeAttr('disabled');
            } 
            if (cl.VISA == 'Y') ctrl.clVisa.e.removeAttr('disabled').attr('checked', cl.VISA == 'Y' ? true : false);
            if (cl.Mastercard == 'Y') ctrl.clMaster.e.removeAttr('disabled').attr('checked', cl.Mastercard == 'Y' ? true : false);
            if (cl.AMEX == 'Y')ctrl.clAME.e.removeAttr('disabled').attr('checked', cl.AMEX == 'Y' ? true : false);
            if (cl.Discover == 'Y')ctrl.clDiscover.e.removeAttr('disabled').attr('checked', cl.Discover == 'Y' ? true : false);

            //Connection Information
            ctrl.clShortName.e.val(clIO.ClientShortName);
            ctrl.striaDesc.e.val(clIO.StriataServerDesc);
            ctrl.striaAddress.e.val(clIO.StriataServerNameOrIP);
            ctrl.striaUser.e.val(clIO.StriataUsername);
            ctrl.striaPass.e.val(clIO.StriataUserPW);
            ctrl.fedDesc.e.val(clIO.FedPayServerDesc);
            ctrl.fedAddress.e.val(clIO.FedPayServerNameOrIP);
            ctrl.fedUser.e.val(clIO.FedPayUsername);
            ctrl.fedPass.e.val(clIO.FedPayUserPW);
            
            //System Preferences
            var subscribeRptUpdate = Boolean(cl.SubscribeRptUpdate);
            ctrl.optinY.e.prop('checked', subscribeRptUpdate);
            ctrl.optinN.e.prop('checked', !subscribeRptUpdate);

            var unsubscribeRptUpdate = Boolean(cl.UnsubscribeRptUpdate);
            ctrl.optoutY.e.prop('checked', unsubscribeRptUpdate);
            ctrl.optoutN.e.prop('checked', !unsubscribeRptUpdate);

            var pMOverrideCustomer = Boolean(cl.PMOverrideCustomer);
            ctrl.printmachaddY.e.prop('checked', pMOverrideCustomer);
            ctrl.printmachaddN.e.prop('checked', !pMOverrideCustomer);
            
            var pMAllowIntro = Boolean(cl.PMAllowIntro);
            ctrl.printachOptinY.e.prop('checked', pMAllowIntro);
            ctrl.printachOptinN.e.prop('checked', !pMAllowIntro);

            ctrl.optindays.e.val(cl.CustomerStatusTimeOut);
            
            var clientDefaultInfo = Boolean(cl.ClientDefaultInfo);
            ctrl.defaultpmY.e.prop('checked', clientDefaultInfo);
            ctrl.defaultpmN.e.prop('checked', !clientDefaultInfo);
            
            var useClientPaymentMethod = Boolean(cl.UseClientPaymentMethod);
            ctrl.accpaysetY.e.prop('checked', useClientPaymentMethod);
            ctrl.accpaysetN.e.prop('checked', !useClientPaymentMethod);


            //Show edit controls - Hide readOnly text
            $.each(ctrl, function(index, value) {
                if (value.e && value.r) {
                    value.e.show();
                    value.r.hide();
                    if(value.showe)
                        value.showe();
                }
            });

            //Set read-only fields - with workspace has status is ACTIVATED - ACTIVATED WITHOUT STRIATA
            if (workspaceData.wp.WorkSpaceStatusName == workspaceStatus.active ||
                workspaceData.wp.WorkSpaceStatusName == workspaceStatus.activeWithoutStriata) {
                
                //hide active button.
                btn.dtActive.hide();
                //client name
                ctrl.clName.e.hide();
                ctrl.clName.r.text(cl.ClientName).show();
                //clientId
                ctrl.clId.e.hide();
                ctrl.clId.r.text(cl.ClientID).show();
                //client contact
                ctrl.clContact.e.hide();
                ctrl.clContact.r.text(cl.ContactName).show();
                //client Email
                ctrl.clEmail.e.hide();
                ctrl.clEmail.r.text(cl.Email).show();
                //client Address 1
                ctrl.clAddress1.e.hide();
                ctrl.clAddress1.r.text(cl.Address1).show();
                //client Telephone 1
                ctrl.clPhone1.e.hide();
                ctrl.clPhone1.r.text(cl.Phone1).show();
                //client City
                ctrl.clCity.e.hide();
                ctrl.clCity.r.text(cl.City).show();
                //client State
                ctrl.clState.e.hide();
                ctrl.clState.r.text(cl.StateProv).show();
                //client Post Code
                ctrl.clPostCode.e.hide();
                ctrl.clPostCode.r.text(cl.PostalCode).show();
                //client Country
                ctrl.clCountry.e.hide();
                ctrl.clCountry.r.text(cl.Country).show();
            }
            
            //Set Image logo
            $('#btn_upload').show();
            if (workspaceData.logo != "") {
                $('#previewLogoImage')
                    .css('background-image', 'url(' + workspaceData.logo + ')')
                    .show();
            } else {
                $('#previewLogoImage').hide();
            }
            
            $.each($('ul.value_1x4'), function (index, value) {
                $($(value).children()[0]).css('margin-right', '');
                $($(value).children()[1]).show();
            });
               
            //if the workspace is activated - completed --> hide the active button
            switch (wp.WorkSpaceStatusName) {
            case workspaceStatus.activeWithoutStriata:
            case workspaceStatus.active:
                btn.dtActive.hide();
                btn.dtSave.show();
                break;
            default:
                btn.dtActive.show();
                break;
            }
            
            if(ctrl.wpstatus.e.text() == workspaceStatus.cloneSaved) {
                ctrl.clName.e.hide();
                ctrl.clId.e.hide();
                ctrl.clName.r.text(cl.ClientName).show();
                ctrl.clId.r.text(wp.ClientID).show();
                ctrl.optindays.e.hide();
                ctrl.optindays.r.text(cl.CustomerStatusTimeOut).show();
                
                //hide upload logo image
                $('#clientFileUpload').hide();
                
                  //System Preferences
                ctrl.optindays.r.text(cl.CustomerStatusTimeOut);

                ctrl.optinY.r.text(subscribeRptUpdate ? 'Yes' : 'No');
                ctrl.optinY.e.hide();
                ctrl.optinY.r.show();
                ctrl.optinY.showr();
                
                ctrl.optoutY.r.text(unsubscribeRptUpdate ? 'Yes' : 'No');
                ctrl.optoutY.e.hide();
                ctrl.optoutY.r.show();
                ctrl.optoutY.showr();
                
                ctrl.printmachaddY.r.text(pMOverrideCustomer ? 'Yes' : 'No');
                ctrl.printmachaddY.e.hide();
                ctrl.printmachaddY.r.show();
                ctrl.printmachaddY.showr();
                
                ctrl.printachOptinY.r.text(pMAllowIntro ? 'Yes' : 'No');
                ctrl.printachOptinY.e.hide();
                ctrl.printachOptinY.r.show();
                ctrl.printachOptinY.showr();
                
                ctrl.defaultpmY.r.text(clientDefaultInfo ? 'Yes' : 'No');
                ctrl.defaultpmY.e.hide();
                ctrl.defaultpmY.r.show();
                ctrl.defaultpmY.showr();

                ctrl.accpaysetY.r.text(useClientPaymentMethod ? 'Yes' : 'No');
                ctrl.accpaysetY.e.hide();
                ctrl.accpaysetY.r.show();
                ctrl.accpaysetY.showr();

                $.each($('ul.value_1x4'), function(index, value) {
                    $($(value).children()[0]).css('margin-right', '200px');
                    $($(value).children()[1]).hide();
                });
            }


            $('#loaderwrapper').hide();
        };

//DISPLAY PREVIEWER IMAGE LOGO WHEN USER SELECT A LOGO IMAGE
        selectionPreviewImage = function(files, value) {
            //Validate file type.
            var item = value.indexOf('.');
            if(item ==-1) {
                alert('File type must be image');
                //reset value
                $('#clientFileUpload').val('');
                return;
            }
            var ext = value.match(/\.(.+)$/)[1];
            switch (ext) {
            case 'jpg':case 'bmp':case 'png':case 'tif': case 'jpeg': case 'gif':
            case 'JPG':case 'BMP':case 'PNG':case 'TIF': case 'JPEG': case 'GIF':    
                break;
            default:
                alert('File type must be image');
                //reset value
                $('#clientFileUpload').val('');
                return;
            }
            
            //validate file size IE10, Chrome, FireFox
            if(files && files.length > 0) { //--> http://stackoverflow.com/questions/7279055/javascript-to-check-filesize-before-upload-in-internet-explorer 
                //alert(files[0].size);
            }

            //FOR IE9 --> Using this example --> http://forums.asp.net/t/1320559.aspx
            if ($.browser.msie && $.browser.version == '9.0' && value) {
                //validate file size
//                var myFSO = new ActiveXObject("Scripting.FileSystemObject");
//                var thefile = myFSO.getFile(value);
//                var size = thefile.size;
//                alert(size + " bytes");

                var newPreview = document.getElementById("previewLogoImage");
                newPreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = value;
                $(newPreview).css('background-image', '').show();
            }
            //FOR IE10, CHROME, FIREFOX OR HIGHER --> support FileReader HTML5 API http://caniuse.com/filereader
            if (files && files.length != 0) {
                var reader = new window.FileReader();
                reader.onloadend = function() {
                    $('#previewLogoImage')
                        .css('background-image', 'url(' + reader.result + ')')
                        .show();
                };
                reader.readAsDataURL(files[0]);
            }
        };

//CHECK PAYMENT BY CARD --> IF PAYMENT BY CARD IS ENABLED --> SHOW THE CARD OPTIONS
//                                                        --> ELSE DISABLE CARD OPTIONS        
        checkpaymentbyCard = function() {
            if (ctrl.clCredit.e.is(':checked')) {
                ctrl.clVisa.e.removeAttr('disabled');
                ctrl.clMaster.e.removeAttr('disabled');
                ctrl.clAME.e.removeAttr('disabled');
                ctrl.clDiscover.e.removeAttr('disabled');
            } else {
                ctrl.clVisa.e.removeAttr('checked').attr('disabled', 'disabled');
                ctrl.clMaster.e.removeAttr('checked').attr('disabled', 'disabled');
                ctrl.clAME.e.removeAttr('checked').attr('disabled', 'disabled');
                ctrl.clDiscover.e.removeAttr('checked').attr('disabled', 'disabled');
            }
        };

//LOAD WORKSPACE DATA FOR EDITTING
        editWorkspace = function(rowId) {
            jQuery('#list').setSelection(sel_row);
            intrnl = true;
            gridRow = jQuery("#list").getRowData(rowId);
            $('#wspId').val(gridRow.WorkspaceId); //Set workspace Id for posting to server.
            var hidsearchid = $('#hidsearchid').val();
            var paramstring = '{seid:"' + hidsearchid + '", key:' + gridRow.WorkspaceId + ', intrnl:true}';
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: ajaxUrl.getWorkspace,
                data: paramstring,
                dataType: "json",
                success: function(data, textStatus) {
                    if (textStatus == "success") {
                        fillWorkspaceForm(jQuery.parseJSON(data.d));
                        $('#loaderwrapper').hide();
                    }
                },
                error: function(data, textStatus) {
                    alert('An error has occured retrieving data!');
                }
            });

            $('#hidID').val(gridRow.pkUser_ID);
            $('#loaderwrapper').show();
            btn.dtSave.button("option", "disabled", false);
            FillUserForm(gridRow);
        };

//RESET FORM WHEN EDITTING IS DONE
        resetForm = function() {

            isChange = false;

            $(document)
                .stop()
                .find('.jfVal,.jValCover')
                .stop()
                .remove()
                .end()
                .find('.jVal,[jVal]')
                .css({ position: '', borderColor: '', left: '0px', top: '0px' })
                .parent()
                .find('.jValRelWrap')
                .remove();

            $(document)
                .stop()
                .find('.jValSpacer,.jValSpacercover')
                .stop()
                .remove()
                .end();

            $('input').css('border', '');

            
            adminJsonData = null;
            ctrl.wpcreateBy.e.text('');
            ctrl.wpcreateDate.e.text('');
            ctrl.wplastModifyDate.e.text('');
            ctrl.wplastModifyBy.e.text('');
            ctrl.clAdminId.e.text('');
            ctrl.clAdminId.r.text('');
            ctrl.clAdminPassword.r.text('');
            ctrl.clAdminPassword.e.text('');
            ctrl.wpstatus.e.text('');
            $('#formSubmitType').val('');
            $('#wspId').val('');
            $('#environment').val('');
            $('activateCloneSaveInfo').val('');
            if ($.browser.msie && $.browser.version == '9.0') {
                var newPreview = document.getElementById("previewLogoImage");
                newPreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = "";
            }

            $('#previewLogoImage').css('background-image',"url('../../Images/DefaultLogo/DefaultSASLogo.png')");
            $('#clientFileUpload').show();
            $('td.req > span').show();
            ctrl.clCredit.e.attr('checked', true);
            ctrl.clWebPay.e.attr('checked', true);
            ctrl.clACH.e.attr('checked', true);
            ctrl.clDebit.e.attr('checked', true);
            ctrl.clCredit.e.attr('checked', true);
            ctrl.clVisa.e.attr('disabled', 'disabled').attr('checked', true);
            ctrl.clMaster.e.attr('disabled', 'disabled').attr('checked', true);
            ctrl.clAME.e.attr('disabled', 'disabled').attr('checked', true);
            ctrl.clDiscover.e.attr('disabled', 'disabled').attr('checked', true);
            $('#btnReset').click();
            btn.dtCancel.show();
            btn.activeCancel.show();
            btn.activate.show();
            btn.dtSave.show();
            btn.dtAdd.show();
            $('#activeForm').show();
            $('#sendEmailForm').hide();
        };
        
//SUBMIT WORKSPACE
        //declare submit handle options.
        //more options can be found by this link http://malsup.com/jquery/form/#options-object
        var submitOptions = {
            success: function(responseText, statusText, xhr, $form) {
                if (responseText != "") {
                    adminJsonData = jQuery.parseJSON(responseText);
                    if(adminJsonData.errorMessage != '') {
                        alert(adminJsonData.errorMessage);
                        $('#loaderwrapper').hide();
                        return;
                    }

                    //if active successfully =--> display the form for user to insert email address.
                    if (adminJsonData.submitType == submitType.active) {
                        $('#activeForm').hide();
                        $('#txtSendingEmailAddress').focus();
                        $('#sendEmailForm').show();
                    }
                    else if(adminJsonData.submitType == submitType.activateCloneSave) {
                        $('#loaderwrapper').hide();
                        alert('Cloning process completed successfully');
                        $('#activeWindowsModal').dialog("close");
                        reloadData('UserData');
                        resetForm();
                    }
                    else
                    {
                        $('#activeWindowsModal').dialog("close");
                        ShowGrid();
                        reloadData('UserData');
                        $('#loaderwrapper').hide();
                        resetForm();
                    }
                }
            }
        };
        
        //Register option for submit form.
        $('#workspaceDetailForm').ajaxForm(submitOptions);

        submitWorkspace = function(submitFormType) {
            //set submit type method: save - addNew - active
            $('#formSubmitType').val(submitFormType);

            //show progress panel
            $('#loaderwrapper').show();

            //asynchronous submit form by Ajax
            $('#workspaceDetailForm').submit();
        };

//COPY FROM EDD SITE
        promptSave = function() {
            btn.dtAdd.button("option", "disabled", false);
            btn.dtSave.button("option", "disabled", false);
            btn.dtCancel.button("option", "label", "Cancel");
        };

        preSave = function() {
            btn.dtAdd.button("option", "disabled", true);
            btn.dtSave.button("option", "disabled", true);
            if (intrnl) {
                btn.dtCancel.button("option", "label", "Back to Workspaces");
            } else {
                btn.dtCancel.button("option", "label", "Back");
            }
        };

        postSave = function() {
            btn.dtAdd.button("option", "disabled", true);
            btn.dtSave.button("option", "disabled", true);
            if (intrnl) {
                btn.dtCancel.button("option", "label", "Back to User");
            } else {
                btn.dtCancel.button("option", "label", "Back");
            }
        };

//ADVANCED SEARCH
        SetSearchParams = function(params) {
            if (params != null) {
                advser[0].p.params = params;
                for (var i = 0; i < params.items.length; i++) {
                    $("#advancedsearch").addRow(params.items[i]);
                }
                if (params.items.length == 0) {
                    $("#advancedsearch").addRow();
                }
            } else {
                $("#advancedsearch").addRow();
            }
        };
        
//MAIN GRID
        function getData(pdata) {
            var hidsearchid = $('#hidsearchid').val();
            if (overridepage > 0) {
                pdata.page = overridepage;
            }
            var paramstring;
            paramstring = advser[0].p.params.items.length > 0 ?
                                '{seid:"' + hidsearchid + '", json:' + JSON.stringify(pdata) + ', search:' + JSON.stringify(advser[0].p.params) + '}'
                               :'{seid:"' + hidsearchid + '", json:' + JSON.stringify(pdata) + ', search:null}';
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: ajaxUrl.getWorkspaces,
                data: paramstring,
                dataType: "json",
                success: function(data, textStatus) {
                    if (textStatus == "success") {
                        var thegrid = $("#list")[0];
                        thegrid.addJSONData(jQuery.parseJSON(data.d));
                    }
                },
                error: function(data, textStatus) {
                    alert('An error has occured retrieving data!');
                }
            });
        };

        GetSelectedItem = function(key, isinternal) {
            intrnl = isinternal;
            var from_outside = true;
            var hidsearchid = $('#hidsearchid').val();
            //var hidsearchid = $('#txtSid').val();
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/Service/Services.aspx/SelectUser",
                data: '{seid:"' + hidsearchid + '", id:"' + key + '", intrnl:' + intrnl + '}',
                dataType: "json",
                success: function(data, textStatus) {
                    $('#loaderwrapper').show();
                    if (textStatus == "success") {
                        var custrow = jQuery.parseJSON(data.d); 
                        if (custrow != null) {
                            ShowDetail();
                            FillUserForm(custrow);
                        }
                    }
                    $('#loaderwrapper').hide();
                },
                error: function(data, textStatus) {
                    alert('An error has occured retrieving data!');
                    $('#loaderwrapper').hide();
                }
            });
        };

        CreateGrid = function() {
            $('#list').jqGrid({
                datatype: function(pdata) {
                    $('#loaderwrapper').show();
                    getData(pdata);
                },
                jsonReader: {
                    root: "rows", //arry containing actual data
                    page: "page", //current page
                    total: "total", //total pages for the query
                    records: "records", //total number of records
                    repeatitems: false
                    //id: "FullName" //index of the column with the PK in it
                },
                colNames: columnNames,
                colModel: columnModel,
                rowNum: 15,
                rowList: [5, 10, 15, 20, 25, 30, 35, 40, 50],
                pager: jQuery('#pager'),
                gridview: false,
                hidegrid: false,
                onPaging: function() { resizeGrid(); },
                resizeStop: function(newwidth, index) {
                    //jqgrid is forcing me to jump thru alot of hoops just to allow me to resize the column and then resize the grid.
                    //this is an ugly solution, but after 4 hours of cranking away at this, this is the best I can do.  
                    var pg = $("#list").getGridParam('page');
                    overridepage = pg;
                    columnModel[index - 1].width = newwidth;
                    columnModel[index - 1].widthOrg = newwidth;
                    SetVCConfig();
                    $("#list").jqGrid('GridUnload');
                    $("#list").jqGrid('GridDestroy');
                    CreateGrid();
                    $("#list").trigger("reloadGrid");
                    overridepage = 0;
                },
                onSelectAll: function(rowIdxArray, sts) {
                },
                onSelectRow: function(rowId) {
                    $("#cb_list").removeAttr("checked");
                },
                gridComplete: function() {
                    var grid = jQuery("#list");
                    var ids = grid.jqGrid('getDataIDs');
                    for (var i = 0; i < ids.length; i++) {
                        var rowId = ids[i];
                        var editbutton = "<img src='/images/edit18.png' alt='chart' title='' class='gridButton' onclick=\"editWorkspace(" + rowId + ");\" />";
                        gridRow = grid.getRowData(rowId);
                        
                        var clone = "<img src='/images/edit18.png' alt='chart' title='' class='gridButton' onclick=\"createCloneSave(" + rowId + ");\" />";
                        if(gridRow.WorkSpaceStatusName == workspaceStatus.activeWithoutStriata ||
                           gridRow.WorkSpaceStatusName == workspaceStatus.active) {
                           grid.jqGrid('setRowData', rowId, { Clone: clone });    
                        }

                        
                        grid.jqGrid('setRowData', rowId, { Edit: editbutton });
                        
                        
                        if (i % 2 !== 0) {
                            var t = $("#" + rowId, grid);
                            t.addClass('alternateRow');
                        }
                    }
                    resizeGrid();
                },
                multiselect: true,
                rownumbers: false,
                sortname: 'CreatedDate',
                sortorder: 'desc',
                viewrecords: true,
                imgpath: '/CSS/themes/neopost/images',
                caption: '',
                width: '100%',
                height: '100%',
                sortable: true
            }).navGrid('#pager', { edit: false, add: false, del: false, refresh: false, view: false, search: false }, {}, {}, {}, { multipleSearch: true, overlay: false });
            $('#list').jqGrid('filterToolbar', { autosearch: true, searchOnEnter: false });

            $("#gbox_list").bind("sortstop", function(event, ui) {
                // you can even get the current permutation!
                // Yes, it looks like you may be grabbing the remapColumns function.
                //    You're not, you get an array of integers back.
                if (ui.item[0].id != 'list_Edit') {
                    grid.jqGrid("getGridParam", "remapColumns");
                    SetVCConfig();
                }
                var pg = $("#list").getGridParam('page');
                overridepage = pg;
                GetVCConfig();
                $("#list").jqGrid('GridUnload');
                $("#list").jqGrid('GridDestroy');
                CreateGrid();
                $("#list").trigger("reloadGrid");
                overridepage = 0;
            });

        };
        
//INITIALIZE PAGE WHEN FIRST LOAD
        $('#workspaceTab')
            .attr('class', 'navon')
            .children('span')
            .attr('class', 'navspanon');
        
        btn.dtAdd.show();
        btn.dtSave.hide();
        getEnvironment();
        PageFilter();
        ctrl.initialize();
        btn.initialize();
    });